import exceptions
from threading import Thread


class AbstractReducer(Thread):
    
    """this class is to provide framework driven functions for user defined maps
    so that the user is not bothered with administrative tasks like writing tuples 
    that are emitted by reduces 
    """
    NON_ESTIMATOR = 'NE'
    ESTIMATOR = 'E'
    
    NON_THRESHOLDABLE = 'NTH'
    THRESHOLDABLE = 'TH'
    
    def __init__(self, key, list_of_values, key_value_dict, estimatable=NON_ESTIMATOR, thresholdable=NON_THRESHOLDABLE):  
        """Saying thats its an Estimator Reducer just indicates to any class
        that the results of this reduce function can be estimated
        
        Saying that the reduce can be thresholded, ie. this reduce does 
        computation which can be thresholded to save processing time
        """
        
        # the critical values for any reduce function
        self.key = key
        self.list_of_values = list_of_values
        self.key_value_dict = key_value_dict
        
        self.estimatable = estimatable
        self.thresholdable = thresholdable
        
        Thread.__init__(self)
    
    
    def run(self):
        """Called by the thread's start function
        """
        
        self.reduce(self.key, self.list_of_values)
    
        
    def reduce(self, key, list_of_values):
        """this is the prototype for the user defined reduce function
        """
        
        raise exceptions.NotImplementedError('Base class doesn\'t implement the Reducer')
        
        
    def emit(self, key, final_list_of_values):
        """this functions will be used by the user map to emit its output, key, value pairs
        """
        
        if key in self.key_value_dict:
            raise exceptions.KeyError('The key %s has already been emitted by the Reduce function')
        
        self.key_value_dict[key] = final_list_of_values
        
